package com.sun.StudentInfo.utils;

import com.sun.StudentInfo.pojo.Vo.CourseVo;
import com.sun.StudentInfo.service.CourseService;
import com.sun.StudentInfo.service.SelectCourseService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

public class CourseSelectUtils {
    private static final String STUDENT_COURSE_LIST = "student_course_list_";
    private static final String COURSE_SELECTED_NUM = "course_selected_num_";

    @Resource
    RedisUtil redisUtil;

    @Resource
    SelectCourseService scService;

    /**
     * 获取课程已选人数
     *
     * @param cid 课程id
     * @return 已选人数
     */
    public int getSelectedNum(String cid) {
        // 从redis中已选课程数
        Object selectedNumFromCache = redisUtil.get(COURSE_SELECTED_NUM + cid);

        // 如果缓存中为空，则从数据库中统计已选人数，然后将已选课程放入缓存中
        int selectedNum;
        if (selectedNumFromCache == null) {
            selectedNum = scService.querySelectedCourseNum(cid);
            redisUtil.set(COURSE_SELECTED_NUM + cid, selectedNum);
        } else {
            selectedNum = (int) selectedNumFromCache;
        }
        return selectedNum;
    }

    /**
     * 获取课程信息
     *
     * @param cid 课程id
     * @param cid 学生id
     * @return 课程信息
     */
    public CourseVo getCourseVoFromCache(String cid, String sid) {
        // 从缓存中获取所有可选的课程信息
        Object object = redisUtil.get(STUDENT_COURSE_LIST + sid);
        if (object == null) {
            return null;
        }
        // 这里要先判空再转换，不然会报空指针异常
        List<CourseVo> courseVoList = (List<CourseVo>) object;

        // 获取与cid匹配的课程信息，获取不到返回null
        for (CourseVo vo : courseVoList) {
            if (vo.getCId().equals(cid)) {
                return vo;
            }
        }
        return null;
    }

}
